<template>


    <el-card v-loading="loading" >
        <template #header>
            <div class="card-header">
                <div class="buttons">
                    <div class="mb-4">
                        <el-button type="primary" round @click="addNew">新增</el-button>
                        <el-button type="success" round @click="update">修改</el-button>
                        <el-button type="danger" round @click="handeleDelete">删除</el-button>
                        <el-button type="warning" round @click="toggleSelection()">清空选择</el-button>
                    </div>
                </div>
            </div>
        </template>
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%; height: 400px;"
            @selection-change="handleSelectionChange" @row-click="handleRowChick">
            <el-table-column type="selection" width="55" />
            <el-table-column property="name" label="岗位名" width="120" />
            <el-table-column label="状态" width="120">
                <template #default="scope">
                    <el-switch v-model="scope.row.enabled" class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        @change="changeEnable(scope.row)" />
                </template>

            </el-table-column>
            <el-table-column property="createTime" label="创建时间" width="240" />
        </el-table>
        <template #footer>
            <div class="example-pagination-block">
                <el-pagination layout="prev, pager, next" :default-page-size="pageSize"
                    v-model:current-page="currentPage" :total="totalSize" @current-change="getJobByPageIm" />
            </div>

        </template>
    </el-card>



    <!-- 更新员工表单 -->
    <el-drawer v-model="drawer_update" title="修改岗位">
        <el-form ref="updateFormRef" style="max-width: 600px" :model="updateForm" :rules="updaterules"
            label-width="auto" class="demo-ruleForm" status-icon>
            <el-form-item label="岗位名" prop="name">
                <el-input v-model="updateForm.name" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitUpdateForm(updateFormRef)">
                    提交
                </el-button>
                <el-button @click="resetUpdateForm(updateFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

    <!-- 新建员工 -->
    <el-drawer v-model="drawer_new" title="新建岗位">
        <el-form ref="newFormRef" style="max-width: 600px" :model="newForm" :rules="newrules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="岗位名" prop="name">
                <el-input v-model="newForm.name" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitNewForm(newFormRef)">
                    提交
                </el-button>
                <el-button @click="resetNewForm(newFormRef)">重置表单</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>


</template>

<script lang="ts" setup>
import { nextTick, onBeforeMount, reactive, ref } from 'vue'
import { ElTable, ElNotification } from 'element-plus'
import { createJob, updateJob, deleteJob, getJobByPage } from '@/api/job';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

interface Job {
    name: string
    id: string
    createTime: string
    enabled: boolean
}

const drawer_new = ref(false)
const drawer_update = ref(false)

function addNew() {
    drawer_new.value = true;
}

function update() {
    if (multipleSelection.value.length != 1) {
        ElNotification({
            title: "Warning",
            message: "请选择单个用户",
            type: "warning"
        })
    } else {
        drawer_update.value = true;
    }

}

const newFormRef = ref<FormInstance>()
const newForm = reactive<Job>({
    name: '',
    enabled: true,
    createTime: '',
    id: ''
})

const updateFormRef = ref<FormInstance>()
const updateForm = reactive<Job>({
    name: '',
    enabled: true,
    createTime: '',
    id: ''
})

const newrules = reactive<FormRules<Job>>({
    name: [
        { required: true, message: '请输入岗位名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ]
})

const updaterules = reactive<FormRules<Job>>({
    name: [
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ]
})


const submitUpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            updateForm.id = multipleSelection.value[0].id
            updateForm.name = updateForm.name || multipleSelection.value[0].name
            updateForm.createTime = multipleSelection.value[0].createTime
            const res = await updateJob(updateForm);
            if (res.status == '204') {
                ElNotification({
                    title: 'Success',
                    message: "修改成功",
                    type: 'success'
                })
                tableData[tableData.findIndex(x => x.id == updateForm.id)] = { ...updateForm }
                drawer_update.value = false
            }
        } else {
            console.log('error submit!', fields)
        }
        loading.value = false
    })
}

const resetUpdateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const submitNewForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const res = await createJob(newForm);
            if (res.status == '201') {
                ElNotification({
                    title: "Success",
                    type: "success",
                    message: "添加成功"
                })
                drawer_new.value = false
                getJobByPageIm()
            } else {
                ElNotification({
                    type: "error",
                    title: "Error",
                    message: '添加失败' + res.data.message
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetNewForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


// 列表管理Starte
const pageSize = 7;
const totalSize = ref(1);
const currentPage = ref(1);
const loading = ref(false)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Job[]>([])
const toggleSelection = (rows?: Job[]) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }
}

const handleSelectionChange = (val: Job[]) => {
    multipleSelection.value = val
}
const handleRowChick = (row) => {
  const selected = multipleSelection.value.some((item) => item.id === row.id)
  if (!selected) {
    multipleSelection.value.push(row)
    multipleTableRef.value.toggleRowSelection(row,true)
  } else {
    const finArr = multipleSelection.value.filter((item) => {
      return item.id !== row.id
    })
    multipleSelection.value = finArr
    multipleTableRef.value.toggleRowSelection(row, false)
  }
}

const tableData: Job[] = reactive([

])



const getJobByPageIm = async () => {
    let params = {
        page: currentPage.value-1,
        size: pageSize
    }
    loading.value = true
    tableData.length = 0
    const res = await getJobByPage(params)
    if (res != null) {
        if (res.status == '200') {
            console.log("获取成功，当前页码：", currentPage.value, "当前页面大小：", pageSize)
            const data = res.data
            totalSize.value = data.totalElements
            for (let i of data.content) {
                tableData.push(i)
            }

        } else {
            console.log("获取失败，当前页码：", currentPage.value, "当前页面大小：", pageSize)
        }
    } else {
        console.log("请求失败")
    }
    nextTick(() => {
        loading.value = false
    })

}
//列表管理end

const changeEnable = async (target) => {
    let temp: Job = {
        name: target.name,
        enabled: target.enabled,
        createTime: target.createTime,
        id: target.id,
    }
    const res = await updateJob(temp);
    if (res.status == '204') {
        ElNotification({
            title: "Success",
            type: "success",
            message: "岗位状态更改成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "用户状态更改失败"
        })
        temp = tableData.find(x => x.id == temp.id)
        temp.enabled = !temp.enabled
    }
}

const handeleDelete = async () => {
    if (multipleSelection.value.length <= 0) {
        ElNotification({
            title: "Warning",
            type: "warning",
            message: "请选择删除对象"
        })
        return
    }
    let deleteArray = []
    for (let i of multipleSelection.value) {
        if (i.id == '1') {
            ElNotification({
                title: "Warning",
                type: "warning",
                message: "不能删除超级管理员"
            })
            return
        }
        deleteArray.push(i.id)
    }
    loading.value = true;
    const res = await deleteJob(deleteArray);
    if (res.status == "200") {
        getJobByPageIm();
        ElNotification({
            title: "Success",
            type: "success",
            message: "删除成功"
        })
    } else {
        ElNotification({
            title: "Error",
            type: "error",
            message: "删除失败"
        })
    }
}

onBeforeMount(() => {
    getJobByPageIm()
})
</script>

<style scoped>
.example-pagination-block+.example-pagination-block {
    margin-top: 10px;
}

.example-pagination-block .example-demonstration {
    margin-bottom: 16px;
}
</style>